const { Comment } = require('../../models/Comment')
const { Article } = require('../../models/Article')

// 添加评论
const add = async (ctx, next) => {
  let comment = ctx.request.body
  let id = comment.articleId
  let res = await Comment.create(comment)
  await Article.updateOne({ id }, {$inc: { comment: 1 }})
  ctx.body = {
    code: 200,
    msg: '评论成功'
  }
}
// 前台通过文章id查询评论
const findCommentFont = async ( ctx, next ) => {
  let { id } = ctx.query
  let res = await Comment.find({ articleId: id })
  if( res.length ){
    ctx.body = {
      code: 200,
      data:res
    }
  }else{
    ctx.body = {
      code: 300,
      msg: "暂无评论"
    }
  }
}

// 后台文章评论查询
const findCommentServer = async (ctx, next) => {
  let {
    page,
    author
  } = ctx.query
  try{
    // 页码进行判断
  if (!page || isNaN(Number(page))) {
    page = 1
  } else {
    page = Number(page)
  }
  // 每一页的条数
  let pageSize = 5
  // 计算总条数
  let res = await Comment.find({
    author
  }).countDocuments()
  let totalPage = res ? Math.ceil(res / pageSize) : 0
  if (page >= totalPage) {
    page = totalPage
  } else if (page < 1) {
    page = 1
  }
  // 计算起始位置
  let start = (page - 1) * pageSize
  let data = await Comment.find({
    author
  }).skip(start).limit(pageSize)
  ctx.body = {
    code: 200,
    total:res,
    page,
    pageSize,
    data
  }
  }catch(err){
    ctx.body = {
      code: 400,
      msg: '没有数据'
    }
  }
  
}

module.exports = {
  add,
  findCommentFont,
  findCommentServer
}
